﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Turtle8
{
    public partial class PostPanel : UserControl
    {
        string postName;
        DateTime startDate;

        public string PostName
        { get { return postName; } }
        public DateTime StartDate
        { get { return startDate; } }

        PostImagesManager imagesManager;
        PostImage currentPostImage;
        bool hasEntryInDB;


        /// <summary>
        /// this Ctor is called when the user wants to create new post 
        /// </summary>
        /// <param name="startDate"></param>
        public PostPanel(DateTime startDate)
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

               postName = string.Empty;
               hasEntryInDB = false;
               this.startDate = startDate;
               imagesManager = new PostImagesManager(this);
               currentPostImage = null;

               //set openFileDialog properties
               openFileDialog.Multiselect = false;
               openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
               openFileDialog.Title = "בחר תמונה...";
               openFileDialog.Filter = "All files (*.*)|*.*|Jpeg|*.jpeg|Jpg|*.jpg|Gif|*.gif |Bmp|*.bmp";

            setPostImageProperties();
        }
        /// <summary>
        /// this Ctor called when the user wants to open an already exist Post.
        /// </summary>
        /// <param name="postName"></param>
        /// <param name="startDate"></param>
        public PostPanel(string postName, DateTime startDate)
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            this.postName = postName;
            this.startDate = startDate;
            imagesManager = new PostImagesManager(this);
            hasEntryInDB = true;

            //set openFileDialog properties
            openFileDialog.Multiselect = false;
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            openFileDialog.Title = "Select image";
            openFileDialog.Filter = "All files (*.*)|*.*|Jpeg|*.jpeg|Jpg|*.jpg|Gif|*.gif |Bmp|*.bmp";

            currentPostImage = imagesManager.getFirst();
            setPostImageProperties();
            initializeTextBoxFields();
        }

        private void NewTahasukaDuringPostCard_Resize(object sender, EventArgs e)
        {
            panelPicNavigator.Location = new Point((splitContainer2.Panel2.Bounds.Width - panelPicNavigator.Width) / 2, 0) ;
            int newPanelsHeight = (this.splitContainer.Panel1.Bounds.Height - panelPostName.Bounds.Height) / 4;
            splitContainerRegionalHistory.Height = newPanelsHeight;
            splitContainerThreats.Height = newPanelsHeight;
            splitContainerEquipment.Height = newPanelsHeight;
            splitContainerComments.Height = newPanelsHeight;

            labelSuccessfulUpdate.Location = new Point((this.splitContainer2.Panel2.Bounds.Width - buttonUpdate.Bounds.Width) / 2, labelSuccessfulUpdate.Location.Y);
        }
        /// <summary>
        /// called by the Ctor
        /// </summary>
          private void initializeTextBoxFields()
          {
              //retreiving all the data for this post.
              SqlCommand selectCmd = new SqlCommand("SELECT * FROM [TahasukaPosts] WHERE (startDate=@startDate AND postName=@postName)", CompanyManager.Connection);
              selectCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
              selectCmd.Parameters.Add("@postName", SqlDbType.NVarChar).Value = postName;
              SqlDataReader reader = selectCmd.ExecuteReader();

              reader.Read();

              //setting all the text fields and the soldiersCtr field
              textBoxPostName.Text = (string)reader["postName"];

              try
              {
                  numericUpDownWarriorsCtr.Value = (Int16)reader["soldierCtr"];
              }
              catch (Exception)
              {
                  numericUpDownWarriorsCtr.Value = 0;
              }

              textBoxRegionalHistory.Text = (string)reader["regionalHistory"];
              textBoxThreats.Text = (string)reader["threats"];
              textBoxEquipment.Text = (string)reader["equipment"];
              textBoxComments.Text = (string)reader["comments"];

              reader.Close();
          }


          /// <summary>
          /// 
          /// </summary>
          private void setPostImageProperties()
          {
              //set currentImage properties
              if (currentPostImage == null)
              {
                  pictureBoxPost.Image = null;
                  textBoxCaption.Text = PostImage.NoImage;
              }
              else
              {

                  pictureBoxPost.Image = currentPostImage.Image;
                  textBoxCaption.Text = currentPostImage.Caption;
              }

              //set ButtonNext and ButtonPrevious Enabled properties
              if (imagesManager.getCount() <= 1)
              {
                  buttonNextImage.Enabled = false;
                  buttonPreviousImage.Enabled = false;
              }
              else
              {
                  buttonNextImage.Enabled = true;
                  buttonPreviousImage.Enabled = true;
              }

              if (currentPostImage == null)
                  textBoxCaption.Enabled = false;
              else textBoxCaption.Enabled = true;
          }

          private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
          {
              // (char)13 is ENTER key
              if (e.KeyChar == (char)13)
                  textBoxPostName_Leave(this, new EventArgs());
          }


          public void saveCurrentPost()
          { buttonUpdate_Click(this, new EventArgs()); }

          public void delete()
          {
              string deleteStr = CompanyManager.getSqlStringFromFile(@"\DELETE\TahasukaPosts.DELETE.sql");
              SqlCommand deleteCmd = new SqlCommand(deleteStr, CompanyManager.Connection);

              deleteCmd.Parameters.Add("@postName", SqlDbType.NVarChar).Value = textBoxPostName.Text;
              deleteCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
              deleteCmd.ExecuteNonQuery();

              deleteCmd.CommandText = CompanyManager.getSqlStringFromFile(@"\DELETE\TahasukaPostImages.DELETE.sql");
              deleteCmd.ExecuteNonQuery();
          }


          private void buttonUpdate_Click(object sender, EventArgs e)
          {
              if (postName == string.Empty || textBoxPostName.Text == string.Empty)
                  MessageBox.Show("שם העמדה אינו חוקי");
              else
              {
                  //updating the postName in [TahasukaPosts].
                  string updateStr = CompanyManager.getSqlStringFromFile(@"\UPDATE\TahasukaPosts.UPDATE.sql");
                  SqlCommand updateCmd = new SqlCommand(updateStr, CompanyManager.Connection);

                  updateCmd.Parameters.Add("@postName", SqlDbType.NVarChar).Value = textBoxPostName.Text;
                  updateCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
                  updateCmd.Parameters.Add("@soldierCtr", SqlDbType.SmallInt).Value = numericUpDownWarriorsCtr.Value;
                  updateCmd.Parameters.Add("@regionalHistory", SqlDbType.NVarChar).Value = textBoxRegionalHistory.Text;
                  updateCmd.Parameters.Add("@threats", SqlDbType.NVarChar).Value = textBoxThreats.Text;
                  updateCmd.Parameters.Add("@equipment", SqlDbType.NVarChar).Value = textBoxEquipment.Text;
                  updateCmd.Parameters.Add("@comments", SqlDbType.NVarChar).Value = textBoxComments.Text;
                  updateCmd.ExecuteNonQuery();

                  imagesManager.updateDB();
                  labelSuccessfulUpdate.Visible = true;
                  timer.Start();
              }
          }

          //next/previous images navigator handlers
          private void buttonPreviousImage_Click(object sender, EventArgs e)
          {
              currentPostImage = imagesManager.getPrevious();
              setPostImageProperties();
          }

          private void buttonNextImage_Click(object sender, EventArgs e)
          {
              currentPostImage = imagesManager.getNext();
              setPostImageProperties();
          }

          private void pictureBoxPost_MouseMove(object sender, MouseEventArgs e)
          {
              if (pictureBoxPost.Image != null)
              {
                  toolTip.Active = true;
                  toolTip.SetToolTip(pictureBoxPost, "לחץ על התמונה להגדלה");
              }
              else toolTip.Active = false;
          }

          private void buttonAddimage_Click(object sender, EventArgs e)
          {
              DialogResult result = openFileDialog.ShowDialog();
              if (result == DialogResult.OK)
                  currentPostImage = imagesManager.addNewImage(openFileDialog.FileName);
              setPostImageProperties();
          }

          private void buttonDeleteImage_Click(object sender, EventArgs e)
          {
              DialogResult result;
              result = MessageBox.Show("האם אתה בטוח כי ברצונך למחוק תמונה זו?", "מחיקת תמונה", MessageBoxButtons.YesNo);
              if (result == DialogResult.Yes)
                  currentPostImage = imagesManager.deleteImage(currentPostImage);

              setPostImageProperties();
          }

          private void textBoxPostName_Leave(object sender, EventArgs e)
          {
              if (textBoxPostName.Text == string.Empty)
                  MessageBox.Show("שם העמדה אינו חוקי");
              else if (!hasEntryInDB)
              {
                  //insert a new post to TahasukaPosts database
                  string insertStr = "INSERT into [TahasukaPosts] VALUES (@postName,@startDate,@soldierCtr,@regionalHistory,@threats,@equipment,@comments)";
                  SqlCommand insertCmd = new SqlCommand(insertStr, CompanyManager.Connection);
                  insertCmd.Parameters.Add("@postName", SqlDbType.NVarChar).Value = textBoxPostName.Text;
                  insertCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
                  insertCmd.Parameters.Add("@soldierCtr", SqlDbType.SmallInt).Value = numericUpDownWarriorsCtr.Value;
                  insertCmd.Parameters.Add("@regionalHistory", SqlDbType.NVarChar).Value = textBoxRegionalHistory.Text;
                  insertCmd.Parameters.Add("@threats", SqlDbType.NVarChar).Value = textBoxThreats.Text;
                  insertCmd.Parameters.Add("@equipment", SqlDbType.NVarChar).Value = textBoxEquipment.Text;
                  insertCmd.Parameters.Add("@comments", SqlDbType.NVarChar).Value = textBoxComments.Text;
                  insertCmd.ExecuteNonQuery();
                  hasEntryInDB = true;
              }
              else
              {
                  //updating the postName in [TahasukaPosts].
                  string updateStr = "UPDATE [TahasukaPosts] SET postName=@newPostName WHERE (startDate=@startDate AND postName=@oldPostName)";
                  SqlCommand updateCmd = new SqlCommand(updateStr, CompanyManager.Connection);
                  updateCmd.Parameters.Add("@newPostName", SqlDbType.NVarChar).Value = textBoxPostName.Text;
                  updateCmd.Parameters.Add("@oldPostName", SqlDbType.NVarChar).Value = postName;
                  updateCmd.Parameters.Add("@startDate", SqlDbType.NVarChar).Value = startDate;
                  updateCmd.ExecuteNonQuery();

                  imagesManager.updateDB(postName, textBoxPostName.Text);
              }

              //setting the new postName.
              postName = textBoxPostName.Text;
          }

          private void textBoxCaption_Leave(object sender, EventArgs e)
          {
              currentPostImage = imagesManager.setCaption(textBoxCaption.Text);
          }

          private void pictureBoxPost_Click(object sender, EventArgs e)
          {
              if (pictureBoxPost.Image != null)
                  new PictureBoxForm(pictureBoxPost.Image, textBoxPostName.Text, textBoxCaption.Text).ShowDialog();
          }

          private void buttonRotate_Click(object sender, EventArgs e)
          {
              pictureBoxPost.Image.RotateFlip(RotateFlipType.Rotate90FlipXY);
              Image img = pictureBoxPost.Image;
              pictureBoxPost.Image = null;
              pictureBoxPost.Image = img;

          }

          private void timer_Tick(object sender, EventArgs e)
          {
              labelSuccessfulUpdate.Visible = false;
          }


    }
}
    


    
